<?php

declare(strict_types=1);

namespace App\Services;

use Hyperf\Di\Annotation\Inject;
use App\Exception\ApiException;
use App\Constants\ErrorCode;
use Qbhy\HyperfAuth\AuthManager;
use App\Model\User;
use App\Model\PointsRanking;
use App\Model\UserVideoViews;
use App\Model\UserFans;

class UserService extends BaseService
{
    /**
     * @Inject
     * @var AuthManager
     */
    protected $auth;

    /**
     * @var string
     */
    protected $verity_prefix = 'login_verify_code_';

    /**
     * @var int
     */
    protected $verity_exp = 180;

    public function login(array $params)
    {
        $codeKey = $this->verity_prefix . $params['hash_key'];
        $redis = redis();
        if (!$redis->get($codeKey)) {
            throw new ApiException(ErrorCode::WARNING, '验证码已过期');
        } elseif ($redis->get($codeKey) != $params['code']) {
            throw new ApiException(ErrorCode::WARNING, '验证码错误');
        }

        $user = User::query()->select('id','level','balance','star_currency','points','avatar','nickname','fullname','birthday','signature','wechat','qq','phone','steam','official_server_id','test_server_id','has_partner_privilege','last_login_at','created_at')->where('account',$params['account'])->first();
        if ($user) {
            if($user->status == User::OFF_STATUS){
                throw new ApiException(ErrorCode::WARNING, '该用户已禁用');
            }

            $check_passwd = md5($params['password'] . $user->salt) == $user->password ? true : false;
            if (!$check_passwd) {
                throw new ApiException(ErrorCode::WARNING, '账号或密码错误');
            }
        } else {
            throw new ApiException(ErrorCode::WARNING, '账号不存在');
        }

        $token = $this->auth->login($user);
        $result['user_info'] = $user;
        $result['auth'] = $this->respondWithToken($token);

        User::query()->where('id', $user->id)->update(['last_login_at' => date('Y-m-d H:i:s')]);      //修改最后登录时间

        return $result;
    }

    /**获取图片验证码
     * @param $params
     * @return array
     */
    public function verifyCode(array $params)
    {
        $config = new \EasySwoole\VerifyCode\Conf();
        $config->setUseCurve($params['curve'] ?? false);
        $config->setUseNoise($params['noise'] ?? false);
        $fontColor = $params['font_color'] ?? "#202223";
        $backColor = $params['back_color'] ?? "#ab9246";
        $config->setFontColor($fontColor);
        $config->setBackColor($backColor);
        $code = new \EasySwoole\VerifyCode\VerifyCode($config);

        //重写验证码
        $imgCode = mt_rand(1000, 9999);
        $result = $code->DrawCode($imgCode);

        //写入缓存 用于其他方法验证 并且设置过期时间
        $redis = redis();
        $redis->set($this->verity_prefix . $result->getCodeHash(), $imgCode, $this->verity_exp);

        //图片
        return ['hash_key' => $result->getCodeHash(), 'verify_img' => $result->getImageBase64()];

    }


    /**
     * 获取令牌数组结构
     *
     * @param $token  令牌 token
     * @return array
     */
    protected function respondWithToken($token)
    {
        return [
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => time() + config('auth.guards.jwt.ttl'),  // 单位为秒，此时的时间戳加过期时间
        ];
    }

    public function userData()
    {
        $user = auth();

        $result = [];

        $result['level'] = $user['level'];

        $currentMonth = date('m');
        $lastMonth = $currentMonth - 1;
        $pointsRanking = PointsRanking::query()->select('month','rank','points')->where('month', $lastMonth)->where('user_id', $user['id'])->first();
        $result['rank'] = $pointsRanking['rank'];
        $result['points'] = $pointsRanking['points'];

        $result['views'] = UserVideoViews::query()->where('user_id', $user['id'])->where('month', $lastMonth)->sum('num');
        $result['fans'] = UserFans::query()->where('user_id', $user['id'])->where('month', $lastMonth)->sum('num');

        $result['month'] = $lastMonth;
        return $result;
    }

    public function getUser()
    {
        $user = auth();

        $result['avatar'] = $user['avatar'];
        $result['nickname'] = $user['nickname'];
        $result['id'] = $user['id'];
        return $result;
    }

    public function getUserInfo()
    {
        $user = auth();
        $user = User::query()->select('avatar','nickname','birthday','gender','province_id','city_id','signature','wechat','qq','phone','steam','official_server_id','has_partner_privilege_official','test_server_id','has_partner_privilege_test','platform_1','platform_nickname_1','homepage_link_1','platform_2','platform_nickname_2','homepage_link_2')->where('id', $user['id'])->get()->toArray();

        return $user;
    }

    public function subUserInfo(array $params)
    {
        $user = auth();

        $file = $params['avatar'];
        if (!$file->isValid()) {
            throw new ApiException(ErrorCode::ERROR, "无效文件");
        }
        $extension = $file->getExtension();     //扩展名
        if(!in_array($extension, ['csv']))
        {
            throw new ApiException(ErrorCode::ERROR, "仅支持CSV格式");
        }
        $relativePath = '/public/images/avatar/';       //相对路径
        $filePath = BASE_PATH . $relativePath;        //存储路径
        if(!is_dir($filePath))
        {
            mkdir($filePath, 0777, true);
        }
        $fileName = $user['nickname'];     //用户昵称作为图片名
        $fullPath = $filePath.$fileName.'.'.$extension;     //完整文件路径
        $file->moveTo($fullPath);
        if (!$file->isMoved()) {
            throw new ApiException(ErrorCode::ERROR, "头像上传失败");
        }

        $data['avatar'] = $fullPath;
        $data['nickname'] = $params['nickname'];
        $data['birthday'] = $params['birthday'];
        $data['gender'] = $params['gender'];
        $data['province_id'] = $params['province_id'];
        $data['city_id'] = $params['city_id'];
        $data['signature'] = $params['signature'];
        $data['wechat'] = $params['wechat'];
        $data['qq'] = $params['qq'];
        $data['phone'] = $params['phone'];
        $data['steam'] = $params['steam'];
        $data['official_server_id'] = $params['official_server_id'];
        $data['has_partner_privilege_official'] = $params['has_partner_privilege_official'];
        $data['test_server_id'] = $params['test_server_id'];
        $data['has_partner_privilege_test'] = $params['has_partner_privilege_test'];

        User::query()->where('id', $user['id'])->update($data);

        return [];
    }

    public function subPlatformInfo(array $params)
    {
        $data['platform_1'] = $params['platform_1'];
        $data['platform_nickname_1'] = $params['platform_nickname_1'];
        $data['homepage_link_1'] = $params['homepage_link_1'];
        $data['platform_2'] = $params['platform_2'];
        $data['platform_nickname_2'] = $params['platform_nickname_2'];
        $data['homepage_link_2'] = $params['homepage_link_2'];

        User::query()->where('id', $user['id'])->update($data);

        return [];
    }

    public function myWallet(array $params)
    {
        $user = auth();

        $user = User::query()->select('star_currency','balance')->where('id', $user['id'])->first();       //重新获取用户信息

        $model = AccountRecord::query()->select('created_at','category','detail','star_currency','star_currency_balance','price','balance','status')->where('type', $params['type']);
        $list = $this->usePage($model)->toArray();

        //前端取值price、balance即可
        if(!empty($list))
        {
            foreach($list as $key=>$val)
            {
                if($params['type']=='star_currency')
                {
                    $list[$key]['price'] = $val['star_currency'];
                    $list[$key]['balance'] = $val['star_currency_balance'];
                }
            }
        }

        return $list;
    }
}